// pages/addAddress/addAddress.js
Page({
  /**
   * 页面的初始数据
   */
  data: {
    name: '',
    region: [],
    checked: false,
    tel: '',
    address: '',
    id: '',
    isUpdate: false
  },
  bindRegionChange: function (e) {
    // console.log('picker发送选择改变，携带值为', e.detail.value)
    this.setData({
      region: e.detail.value
    })
  },
  onChange(event) {
    this.setData({
      checked: event.detail,
    });
  },
  goShowInfo() {
    if (this.data.name === '' || this.data.region.length === 0 || this.data.tel === '' || this.data.address === '') {
      wx.showToast({
        title: '信息不能为空',
        icon: 'error'
      })
    } else {
      this.toDatabase()
      if(!this.data.isUpdate) {
        wx.navigateTo({
          url: '/pages/showInfo/showInfo?isadd=' + "true"
        })
      }else {
        wx.showToast({
          title: '修改成功',
        })
      }
    }

  },
  bindNameChange(event) {
    this.setData({
      name: event.detail.value,
    });
  },
  bindTelChange(event) {
    this.setData({
      tel: event.detail.value,
    });
  },
  bindAddressInfo(event) {
    this.setData({
      address: event.detail.value,
    });
  },
  toDatabase() {
    const db = wx.cloud.database()
    let addressData = {
      name: this.data.name,
      local: this.data.region.join('') + this.data.address,
      tel: this.data.tel,
      state: this.data.checked
    }
    if (!this.data.isUpdate) {
      db.collection('location_list')
        .add({ // 添加数据
          data: addressData
        })
        .then(res => {
          console.log('添加成功', res);
        })
        .catch(err => {
          console.log('添加失败', err);
        })
    } else {
      db.collection('location_list')
        .doc(this.data.id)
        .update({ // 添加数据
          data: addressData
        })
        .then(res => {
          console.log('添加成功', res);
        })
        .catch(err => {
          console.log('添加失败', err);
        })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    if (options.id) {
      this.setData({
        id: options.id,
        isUpdate: true
      })
    }
  },
})